<template>
    <div class="page-shop-cart">
        <div class="manage-wrap bg-white">
            <!-- <div class="btn btn-mobile btn-red-transparent" @click="onClickManage">管理</div> -->
            <div class="btn btn-mobile btn-red-transparent" @click="onClickDelete">删除</div>
        </div>
        <div class="separation"></div>
        
        <!-- 购物车列表 -->
        <CartItem v-for="(product, index) in productList"
            :key="index"
            :select-value="product.spec_id"
            :cover="product.cover"
            :name="product.name"
            :price="product.price"
            :spec="product.spec"
            :product-id="product.product_id"
            :selected="selectPaySpecId[product.spec_id]"
            :count="product.count"
            @select="onSelectCart"
            @count="onCountChange" />

        <!-- 底部按钮 -->
        <div class="fixed-btn-wrap">
            <span class="select-all" @click="onClickAllSelect">
                <span class="icon" :class="[allSelected ? 'color-red' : 'color-font-4']">{{allSelected ? '&#xe69e;' : '&#xe637;'}}</span>
                全选
            </span>
            <div class="price-info">
                <span v-if="mode == 'normal'">总计: ￥{{totalPriceText}}</span>
            </div>
            <div v-if="mode == 'normal'" class="btn btn-mobile btn-large btn-rect btn-white-red" @click="onClickConfirm">
                去结算
                <span class="text-tiny">({{goodsLength}}件)</span>
            </div>
            <div v-else class="btn btn-mobile btn-large btn-rect btn-white-red" @click="onClickDelete">
                删除
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import {
    api,
} from '@/lib/api';
import {
    makeMap,
    currency,
} from '@/lib/utils';
import store from '@/store';
import CartItem from '@/features/shop/cartItem.vue';
import { Component, Vue } from 'vue-property-decorator';
import { ROUTE_NAME } from '@/lib/constant';

@Component({
    name: 'ShopCart',
    components: {
        CartItem,
    },
})
export default class ShopCart extends Vue {
    /** 店铺id */
    public shopId: any = null;

    /** 选中要支付的规格id */
    public selectPaySpecId: any = {};

    /** 选中要删除的规格id */
    public selectDelSpecId: any = {};

    /** 模式 */
    public mode: any = 'normal';

    /** 购物车 */
    public get shopCartMap() {
        return store.state.shop.cart;
    }

    /** 商品详情 */
    public get productDetailMap() {
        return store.state.good.productDetailMap;
    }

    /** 规格 */
    public get specMap() {
        return store.state.good.spec;
    }

    /** 购物车信息 */
    public get cart() {
        const list = [];
        for (const key in this.shopCartMap) {
            list.push(...this.shopCartMap[key]);
        }
        return list;
    }

    /** cart对应的map */
    public get cartMap() {
        return makeMap(this.cart, 'spec_id');
    }

    public get goodsLength() {
        let allCount = 0;
        for (const product of this.productList) {
            allCount += this.selectPaySpecId[product.spec_id] ? product.count : 0;
        }
        return allCount;
    }

    /** 商品列表 */
    public get productList() {
        return this.cart.map((item: any) => {
            const product = this.productDetailMap[item.product_id];
            const spec = this.specMap[item.spec_id];
            if (!product || !spec) {
                return;
            }
            return {
                ...item,
                spec: Object.values(spec.param).join(' '),
                cover: product.cover[0],
                name: product.name,
                price: spec.price,
                product_id: item.product_id,
            };
        }).filter((_: any) => _);
    }

    /** 选中的购物车列表 */
    public get selectedCart() {
        // const map = this.mode === 'normal' ? this.selectPaySpecId : this.selectDelSpecId;
        const map = this.selectPaySpecId;
        return this.cart.filter((item: any) => map[item.spec_id]);
    }

    /** 是否全部选中 */
    public get allSelected() {
        return this.selectedCart.length === this.cart.length && this.cart.length > 0;
    }

    /** 总价格 */
    public get totalPriceText() {
        let result = 0;
        for (const product of this.productList) {
            result += this.selectPaySpecId[product.spec_id] ? product.price * product.count : 0;
        }
        return currency(result);
    }

    /**
     * 点击确认
     */
    public async onClickConfirm() {
        const list = this.cart.filter((item) => this.selectPaySpecId[item.spec_id]);
        if (list.length <= 0) {
            wx.showToast({
                title: '未选择任何商品',
                icon: 'none',
            });
            return;
        }
        const cart = {};
        for (const item of list) {
            if (!cart[item.shopId]) {
                cart[item.shopId] = [];
            }
            cart[item.shopId].push(item);
        }
        store.commit('order/setPendingCart', cart);
        // api.navigateTo({
        //     url: '/pages/product_order/main',
        // });
        api.push({
            name: ROUTE_NAME.PRODUCT_ORDER,
        });
    }

    /**
     * 选中购物车
     */
    public onSelectCart(specId: any) {
        const map = this.selectPaySpecId;
        Vue.set(map, specId, !map[specId]);
    }

    /**
     * 数量更新
     */
    public onCountChange({ selectValue, count }: any) {
        const cart = this.cartMap[selectValue];
        if (cart) {
            cart.count = count;
        }
    }

    /**
     * 选择全部所有
     */
    public onClickAllSelect() {
        const allSelected = this.allSelected;
        const map = this.selectPaySpecId;
        for (const item of this.cart) {
            Vue.set(map, item.spec_id, !allSelected);
        }
    }

    /**
     * 点击管理按钮
     */
    public onClickManage() {
        this.mode = this.mode === 'manage' ? 'normal' : 'manage';
    }

    /**
     * 点击删除按钮
     */
    public async onClickDelete() {
        const list = this.cart.filter((item: any) => !this.selectPaySpecId[item.spec_id]);
        const cart = {};
        for (const item of list) {
            if (!cart[item.shopId]) {
                cart[item.shopId] = [];
            }
            cart[item.shopId].push(item);
        }
        store.commit('utils/startRequest');
        await store.dispatch('shop/updateCart', {
            cart,
        });
        store.commit('utils/endRequest');
    }
}
</script>
<style lang="less">

@import "../../lib/style/mixins.less";

.page-shop-cart {
    min-height: 100%;
    background-color: @color-default-bg;

    .manage-wrap {
        display: flex;
        justify-content: flex-end;
        padding: 10px 15px;
    }

    .fixed-btn-wrap {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        background-color: @color-white;
        .select-all {
            padding: 0 10px 0 15px;
        }
        .price-info {
            flex: 1;
            padding-right: 10px;
            text-align: right;
        }
        .btn {
            width: 116px;
            text-align: center;
        }
    }
}

</style>
